<template>
  <h1>详情页</h1>
  <hr>
  <h1>{{weibo.nickname}}说了:{{weibo.content}}</h1>
  <p>发布于:{{weibo.created}}</p>
  <hr>
  <el-input v-model="comment.content" placeholder="请留下你的评论吧!"></el-input>
  <el-button type="primary" @click="post()" style="margin: 10px;">发表评论</el-button>

  <div v-for="c in CommentArr">
    <h4>{{c.nickname}}评论说:{{c.content}}</h4>
    <span>发布于:{{c.created}}</span>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";
import qs from "qs";

//  用ref定义的 对象定义的变量 ,下边要使用的话都要用value才可以读取
const weibo = ref({});
const comment = ref({content:''});
const CommentArr= ref([]);

 onMounted(()=>{

   // 获取请求路径的参数
   let id = new URLSearchParams(location.search).get('id');
   loadComments(id);
   axios.get('http://localhost:8080/v1/weibos/'+id+'/detail').then((response)=>{
      if (response.data.code == 2002){
        weibo.value = response.data.data;
      }
   })
 })


// 发布评论功能
const post = ()=>{
// 将 (localStorage.user)字符串转化为JSON对象
   let user = getUser();
//    如果没有获取到user数据,请先登录
  if (user == null){
    ElMessage.error("请先登录!");
    router.push("/login");
    return;
  }

//   给评论对象设置评论员与微博Id
  comment.value.userId=user.id;
  comment.value.weiboId=weibo.value.id;

//   向后端发送请求
  let data = qs.stringify(comment.value);
  axios.post('http://localhost:8080/v1/comments/add-new',data).then((response)=>{
     if (response.data.code ==2002){
       ElMessage.success("评论成功!");
     }
  //    评论成功后,需要立即加载评论
    loadComments(weibo.value.id);
  })
}

//定义加载评论的函数,参数是当前微博的id
const loadComments = (id) =>{
  //给后端发请求,查这条微博的评论
  axios.get('http://localhost:8080/v1/comments/'+id).then((response)=>{
    if (response.data.code==2002){
      CommentArr.value = response.data.data;
    }
  })
}

</script>

<style scoped>

</style>